<?php
namespace app\admin\service;

use app\admin\model\AdminRole;

class AdminRoleService extends BaseService
{
	public function __construct(AdminRole $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $where
     * @param $field
     * @param int $page
     * @param int $limit
     * @param string $order
     * @param array $with
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageList(array $where, $field,  int $page, int $limit, string $order='id desc', array $with=[]): array
    {
        return $this->model->where($where)->field($field)->with($with)->page($page, $limit)->order($order)->select()->toArray();
    }

    public function countList(array $where = []): int
    {
        return $this->model->where($where)->count();
    }

    public function getList(array $where, $field = '*',  string $order='id desc', array $with=[]): array
    {
        return $this->model->where($where)->field($field)->with($with)->order($order)->select()->toArray();
    }

    public function getInfo(int $id, $field = '*'): array
    {
        $map = [
            'id' => $id
        ];

        if (is_string($field)) $field = explode(',', $field);

        return $this->getWhereInfo($map,$field);
    }

    public function getWhereInfo(array $where, $field = '*', array $with = []): array
    {
        return $this->model->where($where)->field($field)->with($with)->findOrEmpty()->toArray();
    }

    /**
     * 新增
     */
    public function add($data)
    {
        return $this->model->save($data);
    }

    /**
     * 更新
     */
    public function edit($where,$data){
        return $this->model->where($where)->update($data);
    }

    public function del($id){
        $map = [];
        $map['id'] = $id;
        return $this->model->where($map)->delete();
    }

    /**
     * 更新权限
     * @return bool
     */
    public function savePurviewData()
    {
        $where['group_id'] = input('group_id');
        $menu_purview = input('post.menu_purview/a');

        $base_purview = input('post.base_purview/a');
        $data = array();
        if (!empty($menu_purview)) {
            $data['menu_purview'] = implode(',', $menu_purview);
        }
        if (!empty($base_purview)) {
            $data['base_purview'] = implode(',', $base_purview);
        }
        $status = $this->edit($where,$data);
        if (!$status) {
            return false;
        }
        return true;
    }

}
